//
//  JKComposeViewController.swift
//  新浪微博
//
//  Created by Jack.Lin on 16/7/11.
//  Copyright © 2016年 Jack.Lin. All rights reserved.
//

import UIKit
import SVProgressHUD

class JKComposeViewController: UIViewController {
    
    // 文本编辑视图
//    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var textView: JKComposeTextView!


    // 底部工具栏
    @IBOutlet weak var toolBar: UIToolbar!
    // 标题按钮
    @IBOutlet var titleLabel: UILabel!
    // 工具栏底部约束
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    
    
    lazy var emoticonView: CZEmoticonInputView = CZEmoticonInputView.inputView { [weak self] (emoticon) in
        //print(emoticon)
        
        self?.textView.insertEmoticon(em: emoticon)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.cz_random()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", target: self, action: #selector(close))
        
        setupUI()
        
//      监听键盘通知 - UIWindow.h
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardChagnged),
                                               name: NSNotification.Name.UIKeyboardWillChangeFrame,
                                               object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        
        // 激活键盘
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        textView.resignFirstResponder()
    }

    
    // MARK - 键盘监听方法
    @objc private func keyboardChagnged(n: Notification) {
    
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue(),
            duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
        else {
            return
        }
     
        // 设置底部约束高度
        let offset = view.bounds.height - rect.origin.y
        
        toolbarBottomCons.constant = offset
        
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }

    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    
    // 发布微博
    @objc private func postStatus() {
       
        print("发布微博")
        
//        // 1. 获取微博文字
//        guard let text = textView.text else {
//            return
//        }

        // 1. 获取发送给服务器的表情微博文字
        let text = textView.emoticonText

        
        // 2. 发布微博
        let image: UIImage? = nil //UIImage(named: "icon_small_kangaroo_loading_1")
        
        JKNetworkManager.shared.postStatus(text: text, image: image) { (result, isSuccess) in
            
            SVProgressHUD.setDefaultStyle(.dark)
            
            let message = isSuccess ? "发布成功" : "网络不给力"
            
            SVProgressHUD.showInfo(withStatus: message)
            
            if isSuccess {
               
                DispatchQueue.main.after(when: DispatchTime.now() + 1) {
                
                    SVProgressHUD.setDefaultStyle(.light)
                    
                    self.close()
                }
            }
            
        }
    }
    
    lazy var sendButton: UIButton = {
    
        let btn = UIButton()
        
        btn.setTitle("发布", for: [])
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        
        btn.setTitleColor(UIColor.white(), for: [])
        btn.setTitleColor(UIColor.gray(), for: .disabled)
        
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: [])
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 35)
        
        btn.addTarget(self, action: #selector(postStatus) , for: .touchUpInside)
        
        return btn
    }()
    
    // 切换表情键盘
    @objc private func emoticonKeyboard() {
        // textView.inputView 就是文本框的输入视图
        // 如果使用系统默认的键盘, 输入视图为 nil
        
        // 1> 测试键盘视图 - 视图的宽度可以随便, 就是屏幕的宽度
        let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 253))
        keyboardView.backgroundColor = UIColor.blue()
        
        // 2> 设置键盘视图
//        textView.inputView = (textView.inputView == nil) ? keyboardView : nil
        textView.inputView = (textView.inputView == nil) ? emoticonView : nil

        
        // 3> !!! 刷新键盘视图
        textView.reloadInputViews()
        
    }
}

// MARK - UITextViewDelegate

extension JKComposeViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText()
    }
}


private extension JKComposeViewController {

    func setupUI() {
    
       view.backgroundColor = UIColor.white()
        
        setupNavigationBar()
        setupToolbar()
    }
    // 设置工具栏
    func setupToolbar() {
       
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]

        var items = [UIBarButtonItem]()
        
        for s in itemSettings {
            guard let imageName = s["imageName"] else {
                continue
            }
            
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            
            let btn = UIButton()
            
            btn.setImage(image, for: [])
            btn.setImage(imageHL, for: .highlighted)
            
            btn.sizeToFit()
            
            // 判断 actionName
            if let actionName = s["actionName"] {
             
                // 给按钮添加监听方法
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            
            // 追加按钮
            items.append(UIBarButtonItem(customView: btn))
            
            // 追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
        }
        // 删除末尾弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    func setupNavigationBar() {
     
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
      
        navigationItem.titleView = titleLabel
        
        sendButton.isEnabled = false
        
    }
}
